﻿#include "mainui.h"
#include "ui_mainui.h"
#include "privatechat.h"
#include <direct.h>
#include "personinfoui.h"
#include <QWidget>
#include <QDesktopWidget>

MainUI::MainUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainUI)
{
    ui->setupUi(this);
    setWindowTitle(" ");
    setWindowFlags(Qt::FramelessWindowHint);//将窗口标题去掉
    QString folderPath = "D://ChatRecord";

    if (0 != access(folderPath.toStdString().c_str(), 0))
    {
        // if this folder not exist, create a new one.
        mkdir(folderPath.toStdString().c_str());   // 返回 0 表示创建成功，-1 表示失败
    }
    m_ac1.setIcon(QIcon(":/res/search.png"));
    ui->friendId->addAction(&m_ac1,QLineEdit::LeadingPosition);//添加到左侧
    ui->search_list->hide();
    ui->search_list->setIconSize(QSize(50,50));
}

MainUI::~MainUI()
{
    delete ui;
}

MainUI& MainUI::getInstance()
{
    static MainUI mu;
    return mu;
}

void MainUI::loadFriend(QList<userInfo> ulist)
{
    ui->friend_list->clear();
    for(int i=0;i<ulist.size();++i)
    {
        if(ulist[i].online == 1)
        {
            QString name = QString("%1").arg(ulist[i].name);
            QString headurl = OpDb::getInstance().getHeadPath(ulist[i].name);
            QString nickname = OpDb::getInstance().getNickName(ulist[i].name);
            QIcon icon(headurl);
            QString text = nickname+"("+ name +")";
            QListWidgetItem* item = new QListWidgetItem(icon,text);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(255,255,255));
            ui->friend_list->setIconSize(QSize(50,50));
            ui->friend_list->insertItem(0,item);
        }
        else {
            QString name = QString("%1").arg(ulist[i].name);
            QString headurl = OpDb::getInstance().getHeadPath(ulist[i].name);
            QString nickname = OpDb::getInstance().getNickName(ulist[i].name);
            QIcon icon(headurl);
            QString text = nickname+"("+ name +")";
            QListWidgetItem* item = new QListWidgetItem(icon,text);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(200,200,200));
            ui->friend_list->setIconSize(QSize(50,50));
            ui->friend_list->addItem(item);
        }
    }
}

void MainUI::loadGroup(QList<groupinfo> info)
{
    for(auto x:info)
    {
        QString text = QString(x.gname) + "("+ QString(x.gid) + ")";
        QIcon icon(x.ghead);
        QListWidgetItem* item = new QListWidgetItem(icon,text);
        item->setSizeHint(QSize(210,60));
        item->setBackground(QColor(255,255,255));
        ui->list_group->addItem(item);
    }
    ui->list_group->setIconSize(QSize(50,50));
}

void MainUI::updateFriendList(userInfo u,int msg,QString strmsg)
{ 
    if(msg == -1)//他人的消息
    {
        QString extra = QString(strmsg);
        QList<QListWidgetItem*> list = ui->friend_list->findItems(u.name,Qt::MatchContains);
        if(list.size()!=0)
        {
            ui->friend_list->removeItemWidget(list[0]);
            QString name = QString("%1").arg(u.name);
            QString headurl = OpDb::getInstance().getHeadPath(name);
            QString nickname = OpDb::getInstance().getNickName(name);
            QIcon icon(headurl);
            QString text = nickname+"("+ name +")";
            QString text2 = QString("%1\n%2:%3").arg(text).arg(text).arg(extra);
            QListWidgetItem* item = new QListWidgetItem(icon,text2);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(0,255,0));
            ui->friend_list->insertItem(0,item);
            delete list[0];
        }
    }
    else if(msg == -2)//自己的消息
    {
        QString extra = QString(strmsg);
        QList<QListWidgetItem*> list = ui->friend_list->findItems(u.name,Qt::MatchContains);
        if(list.size()!=0)
        {
            ui->friend_list->removeItemWidget(list[0]);
            QString name = QString("%1").arg(u.name);
            QString headurl = OpDb::getInstance().getHeadPath(name);
            QString nickname = OpDb::getInstance().getNickName(name);
            QIcon icon(headurl);
            QString text = nickname+"("+ name +")";
            QString text2 = QString("%1\n%2").arg(text).arg(extra);
            QListWidgetItem* item = new QListWidgetItem(icon,text2);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(255,255,255));
            ui->friend_list->insertItem(0,item);
            delete list[0];
        }
    }
    else if(msg==ONLINE)
    {
        QList<QListWidgetItem*> list = ui->friend_list->findItems(u.name,Qt::MatchContains);
        if(list.size()!=0)
        {
            ui->friend_list->removeItemWidget(list[0]);
            QString name = QString("%1").arg(u.name);
            QString headurl = OpDb::getInstance().getHeadPath(name);
            QString nickname = OpDb::getInstance().getNickName(name);
            QIcon icon(headurl);
            QString text = nickname+"("+ name +")";
            QListWidgetItem* item = new QListWidgetItem(icon,text);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(255,255,255));
            ui->friend_list->insertItem(0,item);
            delete list[0];
        }
    }
    else if(msg == OFF_ONLINE)
    {
        QList<QListWidgetItem*> list = ui->friend_list->findItems(u.name,Qt::MatchContains);
        if(list.size()!=0)
        {
            QString text = list[0]->text();
            ui->friend_list->removeItemWidget(list[0]);
            QString name = QString("%1").arg(u.name);
            QString headurl = OpDb::getInstance().getHeadPath(name);
            QIcon icon(headurl);
            QListWidgetItem* item = new QListWidgetItem(icon,text);
            item->setSizeHint(QSize(210,60));
            item->setBackground(QColor(200,200,200));
            ui->friend_list->addItem(item);
            delete list[0];
        }
    }
    ui->friend_list->repaint();
    ui->friend_list->setIconSize(QSize(50,50));
}

void MainUI::updateGroupList(userInfo u, int msg, QString strmsg,QString gname)
{
    if(msg==1)//注册群成功后更新
    {
        QString text = QString(u.pwd) + "("+ QString(u.name) + ")";
        QIcon icon(strmsg);
        QListWidgetItem* item = new QListWidgetItem(icon,text);
        item->setSizeHint(QSize(210,60));
        item->setBackground(QColor(255,255,255));
        ui->list_group->addItem(item);
    }
    else if(msg==2)//更新群消息 别人发的
    {
        QList<QListWidgetItem*> list = ui->list_group->findItems(gname,Qt::MatchContains);
        if(list.isEmpty())return;
        QIcon gicon = list[0]->icon();
        QString nickname = OpDb::getInstance().getNickName(QString(u.pwd));
        QString text = gname+"\n"+nickname+":"+strmsg;
        ui->list_group->removeItemWidget(list[0]);
        QListWidgetItem* item = new QListWidgetItem(gicon,text);
        item->setSizeHint(QSize(210,60));
        item->setBackground(QColor(0,255,0));
        ui->list_group->insertItem(0,item);
        delete list[0];
    }
    else if(msg == 3)//自己发的
    {
        QList<QListWidgetItem*> list = ui->list_group->findItems(gname,Qt::MatchContains);
        if(list.isEmpty())return;
        QIcon gicon = list[0]->icon();
        QString text = gname+"\n"+strmsg;
        ui->list_group->removeItemWidget(list[0]);
        QListWidgetItem* item = new QListWidgetItem(gicon,text);
        item->setSizeHint(QSize(210,60));
        item->setBackground(QColor(255,255,255));
        ui->list_group->insertItem(0,item);
        delete list[0];
    }
    ui->list_group->setIconSize(QSize(50,50));
}

void MainUI::setNickName(QString name)
{
    QString nickname =  OpDb::getInstance().getNickName(name);
    ui->nickname->setText(nickname);
}

void MainUI::setHead(QString uname)
{
    QString headurl = OpDb::getInstance().getHeadPath(uname);
    QString str = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
    ui->headimg->setStyleSheet(str);
}

bool MainUI::getStatus(QString name)
{
    QList<QListWidgetItem*> list = ui->friend_list->findItems(name,Qt::MatchContains);
    if(list.size()!=0)
    {
        if(list[0]->background()==QColor(200,200,200))
        {
            return false;
        }
    }
    return true;
}

QListWidget* MainUI::getFriendList()
{
    return ui->friend_list;
}

QString MainUI::getNickName()
{
    return  ui->nickname->text();
}

void MainUI::on_btn_addFriend_clicked()//添加好友功能
{
    QString id = ui->friendId->text();
    if(id=="")
    {
        QMessageBox::information(this,"警告","账号不能为空");
        return;
    }

    //若此好友已在你的好友列表  则提示已经是好友  否则才发送好友请求
    QList<QListWidgetItem*> list = ui->friend_list->findItems(id,Qt::MatchContains);
    if(list.size()!=0)
    {
        QMessageBox::information(this,"提示","此人已经是你的好友了");
        return;
    }
    PDU *pdu = makePDU(0);
    pdu->msgType = ADD_FRIEND;
    strcpy(pdu->friendId, id.toStdString().c_str());
    //QMessageBox::information(NULL,"客户端",QString("%1").arg(pdu->friendId));
    qDebug()<<pdu->friendId<<endl;//存放需要加的人的id
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    userInfo u;
    strcpy(u.name,Widget::getInstance().getName().toStdString().c_str());//存放发送好友请求的人的id
    Widget::getInstance().getTcpSocket().write((char*)&u,sizeof (u));
    qDebug()<<u.name<<endl;
    delete pdu;
    pdu = nullptr;

    QMessageBox::information(this,"提示","请求已发送");
    ui->friendId->clear();
}


void MainUI::on_MainUI_destroyed()
{

}


void MainUI::on_pushButton_clicked()//打开个人信息
{
    QString name = Widget::getInstance().getName();
    PersonInfoUI* pui = new PersonInfoUI(nullptr);
    pui->initUserInfo(name);
    pui->show();
}


void MainUI::mousePressEvent(QMouseEvent *event)
{
    isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
    last = event->globalPos();
}

void MainUI::mouseMoveEvent(QMouseEvent *event)
{
    if (isPressedWidget)
    {
        int dx = event->globalX() - last.x();
        int dy = event->globalY() - last.y();
        last = event->globalPos();
        move(x()+dx, y()+dy);
    }
}

void MainUI::mouseReleaseEvent(QMouseEvent *event)
{
    int dx = event->globalX() - last.x();
    int dy = event->globalY() - last.y();
    move(x()+dx, y()+dy);
    isPressedWidget = false; // 鼠标松开时，置为false
}

void MainUI::on_toolButton_2_clicked()
{
    close();
    exit(0);
}

void MainUI::on_friend_list_itemDoubleClicked(QListWidgetItem *item)//双击某个好友
{
    item->setSelected(false);
    QString text = item->text()+"\n";
    QStringList listname = text.split("\n");
    if(item->backgroundColor()==QColor(0,255,0))
    {
        item->setBackground(QColor(255,255,255));
    }

    QList<PrivateChat*>list = Widget::getInstance().getPrivateChatList();
    //若原来存在 先隐藏别的 在显示出来当前的
    for(auto x : list)
    {
        x->hide();
    }
    for(auto x : list)
    {
        if(x->getObjName()==listname[0])
        {
            x->raise();
            x->show();
            return;
        }
    }

    QString name = listname[0];
    PrivateChat* privateChat = new PrivateChat;
    privateChat->setObjName(name);
    privateChat->insertFrienNameToList(name);
    privateChat->setSelectFriend(name);
    //将新的朋友加入list列表
    for(auto x : list)
    {
        x->insertFrienNameToList(name);
        x->setSelectFriend(name);
    }
    //查找有无聊天记录
    QString str(name);
    int i = str.indexOf('(');
    str =str.replace(")","");
    str = str.mid(i+1);
    QString filename = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(str);

    QFile file(filename);
    if(file.exists())
    {
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this,"警告","打开文件失败");
            return;
        }
        char info[1024];
        char info2[1024];
        while(!file.atEnd())
        {
            memset(info,0,1024);
            memset(info2,0,1024);
            file.readLine(info,1024);
            QString msg2="";
            while(1)
            {
                file.readLine(info2,1024);
                msg2 += QString(info2);
                QString content(info2);
                if(content.endsWith("わ\r\n"))
                {
                    break;
                }
            }
            QString msg = QString(info)+"&" + msg2;
            privateChat->restorChatRecord(msg);
        }

        file.close();
    }
    //将别的再聊的朋友加入到新的窗口
    for(auto x : list)
    {
        if(x->getObjName()!=name){
            privateChat->insertFrienNameToList(x->getObjName());
            //x->setSelectFriend(name);
        }

    }
    privateChat->raise();
    privateChat->show();
    Widget::getInstance().getPrivateChatList().append(privateChat);
}

void MainUI::on_toolButton_clicked()
{
    hide();
}

void MainUI::on_friendId_textChanged(const QString &arg1)//当搜索文本变化时显示在界面
{
    ui->search_list->clear();
    if(arg1=="")
    {
        ui->friend_list->raise();
        ui->friend_list->show();
        return;
    }
    m_listwidgetitem = ui->friend_list->findItems(arg1,Qt::MatchContains);
    ui->friend_list->hide();
    if(!m_listwidgetitem.isEmpty())
    {
        for(int i=0;i<m_listwidgetitem.size();++i)
        {
            QIcon icon = m_listwidgetitem[i]->icon();
            QString info = m_listwidgetitem[i]->text();
            QListWidgetItem* item = new QListWidgetItem(icon,info);
            item->setSizeHint(QSize(210,60));
            item->setBackground(m_listwidgetitem[i]->background());
            ui->search_list->insertItem(0,item);
        }
        ui->search_list->repaint();
        ui->search_list->raise();
        ui->search_list->show();
    }
}

void MainUI::on_search_list_itemDoubleClicked(QListWidgetItem *item)//双击搜索结果
{
    item->setSelected(false);
    QString text = item->text()+"\n";
    QStringList listname = text.split("\n");
    if(item->backgroundColor()==QColor(0,255,0))
    {
        item->setBackground(QColor(255,255,255));
        QList<QListWidgetItem*> list = ui->friend_list->findItems(item->text(),Qt::MatchContains);
        if(!list.isEmpty())list[0]->setBackgroundColor(QColor(255,255,255));
    }
    QList<PrivateChat*>list = Widget::getInstance().getPrivateChatList();
    //若原来存在 先隐藏别的 在显示出来当前的
    for(auto x : list)
    {
        x->hide();
    }
    for(auto x : list)
    {
        if(x->getObjName()==listname[0])
        {
            x->raise();
            x->show();
            return;
        }
    }

    QString name = listname[0];

    PrivateChat* privateChat = new PrivateChat;
    privateChat->setObjName(name);
    privateChat->insertFrienNameToList(name);
    privateChat->setSelectFriend(name);
    //将新的朋友加入list列表
    for(auto x : list)
    {
        x->insertFrienNameToList(name);
        x->setSelectFriend(name);
    }
    //查找有无聊天记录
    QString filename = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(name);
    QFile file(filename);
    if(file.exists())
    {
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this,"警告","打开文件失败");
            return;
        }
        char info[1024];
        char info2[1024];
        while(!file.atEnd())
        {
            memset(info,0,1024);
            memset(info2,0,1024);
            file.readLine(info,1024);
            QString msg2="";
            while(1)
            {
                file.readLine(info2,1024);
                msg2 += QString(info2);
                QString content(info2);
                if(content.endsWith("わ\r\n"))
                {
                    break;
                }
            }
            QString msg = QString(info)+"&" + msg2;
            privateChat->restorChatRecord(msg);
        }
        file.close();
    }
    //将别的再聊的朋友加入到新的窗口
    for(auto x : list)
    {
        if(x->getObjName()!=name){
            privateChat->insertFrienNameToList(x->getObjName());
            //x->setSelectFriend(name);
        }

    }

    privateChat->raise();
    privateChat->show();
    Widget::getInstance().getPrivateChatList().append(privateChat);
}



void MainUI::on_pushButton_2_clicked()//注册群聊
{
    bool ok;
    QString text = QInputDialog::getText(this,"提示","请输入群名",QLineEdit::Normal,0,&ok);
    if(ok && !text.isEmpty())
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = REG_GROUP;
        userInfo u;
        memset(&u,0,sizeof (u));
        QString username = Widget::getInstance().getName();
        strcpy(u.name,text.toStdString().c_str());
        strcpy(u.pwd,username.toStdString().c_str());
        Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
        Widget::getInstance().getTcpSocket().write((char*)&u,sizeof (u));
        delete pdu;
        pdu = nullptr;
    }
}

void MainUI::on_list_group_itemDoubleClicked(QListWidgetItem *item)//双击群聊
{
    item->setSelected(false);
    QString text = item->text()+"\n";
    QStringList listname = text.split("\n");
    if(item->background()==QColor(0,255,0))
        item->setBackground(QColor(255,255,255));
    QList<QGroupChat*> list = Widget::getInstance().getGroupChatList();
    for(auto x:list)
    {
        if(x->getGroupName()==listname[0])
        {
            x->raise();
            x->show();
            return;
        }
    }
    QGroupChat* gc = new QGroupChat;
    gc->setGroupName(listname[0]);
    Widget::getInstance().getGroupChatList().append(gc);
    PDU* pdu = makePDU(0);
    pdu->msgType = LOAD_GROUP_PERSON;
    QString recvobj = listname[0];//获取群聊账号
    int i = recvobj.indexOf('(');
    recvobj =recvobj.replace(")","");
    recvobj = recvobj.mid(i+1);
    strcpy(pdu->friendId,recvobj.toStdString().c_str());
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    gc->setGroupNotify(OpDb::getInstance().getGroupNotify(recvobj));
    gc->show();
    delete pdu;
    pdu = nullptr;

}
